package com.lc.pda.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.pda.dao.WmsShipmentMapper;
import com.lc.pda.dto.DeliveryDTO;
import com.lc.pda.dto.MaterialDTO;
import com.lc.pda.entity.WmsInventory;
import com.lc.pda.entity.WmsShipment;
import com.lc.pda.entity.WmsShipmentDetail;
import com.lc.pda.entity.WmsTask;
import com.lc.pda.exception.ApplicationException;
import com.lc.pda.service.WmsInventoryService;
import com.lc.pda.service.WmsShipmentService;
import com.lc.pda.service.WmsTaskService;
import com.lc.pda.util.Enums;
import com.lc.pda.util.OrderNumberUtil;
import com.lc.pda.util.RestResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 出库单主表 服务实现类
 * </p>
 *
 * @author zww
 * @since 2023-07-06
 */
@Service
public class WmsShipmentServiceImpl extends ServiceImpl<WmsShipmentMapper, WmsShipment> implements WmsShipmentService {

    @Resource
    private WmsTaskService taskService;
    @Resource
    private WmsInventoryService inventoryService;

    @Override
    public RestResult callMaterial(List<MaterialDTO> materialDTOList) {
        for (MaterialDTO materialDTO : materialDTOList) {
            WmsShipmentDetail shipmentDetail = new WmsShipmentDetail();
        }
        WmsShipment shipment = new WmsShipment()
                .setShipmentCode(OrderNumberUtil.orderNumber("OUT"))
                .setShipmentType("")
                .setShipmentStatus("")
                .setReviewer(materialDTOList.get(0).getOperator())
                .setCreateBy(materialDTOList.get(0).getOperator())
                .setCreateTime(new Date())
                .setUpdateBy(materialDTOList.get(0).getOperator())
                .setUpdateTime(new Date());
        //todo 转发给WMS生成出库任务


        return null;
    }

    @Override
    @Transactional
    public RestResult delivery(DeliveryDTO deliveryDTO) {
        //扣减数据
        BigDecimal deliveryQty = new BigDecimal(deliveryDTO.getDeliveryQty());
        if (BigDecimal.ZERO.compareTo(deliveryQty) >= 0) {
            return RestResult.error("出库数量不能为空或零！");
        }
        List<WmsTask> list = taskService.list(Wrappers.<WmsTask>lambdaQuery()
                .eq(WmsTask::getTrayCode, deliveryDTO.getTrayCode())
                .eq(WmsTask::getTaskType, Enums.TaskTypeEnum.out.getType())
                .lt(WmsTask::getTaskStatus, Enums.TaskStatusEnum.finish.getStatus()));
        if (list.isEmpty()) {
            return RestResult.error("无此托盘未完成任务！");
        }
        BigDecimal totalQty = list.stream().map(WmsTask::getPlanQty).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (deliveryQty.compareTo(totalQty) > 0) {
            return RestResult.error("失败！拣选数量大于出库数量！");
        }
        //1.同托盘存在多条任务时处理
//        taskListHandler(deliveryQty, list);
        //2.一个托盘只有一个任务时
        taskHandler(deliveryQty, list.get(0));

        return RestResult.success("拣选完成");
    }

    private void taskHandler(BigDecimal deliveryQty, WmsTask task) {
        WmsInventory inventory = inventoryService.getById(task.getStockId());
        if (deliveryQty.compareTo(inventory.getQty()) == 0) {
            //库存扣减全部，完成任务
            if (!inventoryService.deleteAndToHis(inventory.getInventoryId())) {
                throw new ApplicationException(500, "库存清除转移失败！");
            }
        } else {
            //扣减部分库存，完成任务
            inventory.setQty(deliveryQty.abs());
            inventoryService.updateById(inventory);
        }
        taskService.updateById(task);
    }

    private void taskListHandler(BigDecimal deliveryQty, List<WmsTask> list) {
        for (WmsTask task : list) {
            WmsInventory inventory = inventoryService.getById(task.getStockId());
            deliveryQty = deliveryQty.subtract(inventory.getQty());
            if (BigDecimal.ZERO.compareTo(deliveryQty) > 0) {
                //扣减部分库存，完成任务
                inventory.setQty(deliveryQty.abs());
                inventoryService.updateById(inventory);
            } else {
                //库存扣减全部，完成任务
                if (!inventoryService.deleteAndToHis(inventory.getInventoryId())) {
                    throw new ApplicationException(500, "库存清除转移失败！");
                }
            }
            task.setTaskStatus(Enums.TaskStatusEnum.finish.getStatus());
        }
        taskService.updateBatchById(list);
    }
}
